package com.sphd.emanu.fragment.contacts;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseFragment;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.view.siderbar.CharacterParser;
import com.sphd.emanu.view.siderbar.PinyinComparator;
import com.sphd.emanu.view.siderbar.SideBar;
import com.sphd.emanu.view.siderbar.SortAdapter;
import com.sphd.emanu.view.siderbar.SortModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.pedant.SweetAlert.SweetAlertDialog;


/**
 * @Author Hu
 * @Time 2017/4/6 -- 15:00.
 * @Email 87683202@qq.com
 */
public class ContactsFragment extends MVPBaseFragment<ContactsContract.View, ContactsPresenter> implements ContactsContract.View {
    @BindView(R.id.country_lvcountry)
    ListView sortListView;
    @BindView(R.id.dialog)
    TextView dialog;
    @BindView(R.id.sidrbar)
    SideBar sidrbar;
    Unbinder unbinder;
    @BindView(R.id.contacts_search)
    MaterialEditText contactsSearch;


    private SortAdapter adapter;
    Bundle bundle;
    User user;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> sourceDateList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private static final String TAG = "ContactsFragment";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_contacts;
    }

    private void initEvent() {
        contactsSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                contactsSearch.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);

            }
        });
        // 根据输入框输入值的改变来过滤搜索
        contactsSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        sortListView.setOnItemClickListener((parent, view, position, id) -> {
            //这里要利用adapter.getItem(position)来获取当前position所对应的对象
            new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("确定要拨打电话" + ((SortModel) adapter.getItem(position)).getName() + "吗？")
                    .setConfirmText("确定").setConfirmClickListener(sweetAlertDialog1 -> {
                call(((SortModel) adapter.getItem(position)).getPhone());
                sweetAlertDialog1.dismiss();
            }).setCancelText("算了").show();


        });
        //设置右侧触摸监听
        sidrbar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);

                }

            }

        });
    }

    protected void initView() {
        unbinder = ButterKnife.bind(this, rootView);
        bundle = getArguments();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        initAdapter();
        initEvent();
        setUserVisibleHint(true);
    }

    /**
     * 调用拨号界面
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void initData() {
        showProgressDialog();
        mPresenter.selectUserPhone(user.getOid());
    }

    private void initAdapter() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sidrbar.setTextView(dialog);
        sourceDateList = new ArrayList<>();
        adapter = new SortAdapter(context, sourceDateList);
        sortListView.setAdapter(adapter);

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : sourceDateList) {
                String name = sortModel.getName();
                String phone = sortModel.getPhone();
                if ((name.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(name).startsWith(filterStr.toString())) || (phone.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(phone).startsWith(filterStr.toString()))) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void setListBean(List<User> userList) {
        dissProgressDialog();
        sourceDateList.clear();
        for (User user : userList) {
            SortModel sortModel = new SortModel();
            sortModel.setName(user.getUsername());
            sortModel.setPhone(user.getLogonname());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(user.getUsername());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            sourceDateList.add(sortModel);
        }
        // 根据a-z进行排序源数据
        Collections.sort(sourceDateList, pinyinComparator);
        adapter.notifyDataSetChanged();
    }


}
